<template>
  <div class="one-click-case-list-container">
    <!-- 页面头部 -->
    <a-page-header 
      class="page-header" 
      title="一键委案案件列表" 
      sub-title="选择待审核案件进行一键委案操作"
      @back="() => $router.go(-1)"
    >
      <template #extra>
        <a-button @click="handleRefresh" :loading="loading">
          <template #icon><ReloadOutlined /></template>
          刷新
        </a-button>
      </template>
    </a-page-header>

    <!-- 搜索和筛选区域 -->
    <a-card class="filter-card" :body-style="{ padding: '20px' }">
      <a-form layout="inline" :model="searchForm" @finish="handleSearch">
        <a-form-item label="批次名称">
          <a-input 
            v-model:value="searchForm.batchName" 
            placeholder="请输入批次名称"
            style="width: 200px;"
          />
        </a-form-item>
        <a-form-item label="案件状态">
          <a-select 
            v-model:value="searchForm.state" 
            placeholder="请选择状态"
            style="width: 150px;"
            allowClear
          >
            <a-select-option value="TO_AUDIT">待审核</a-select-option>
            <a-select-option value="PRE_AUDIT_SUCCESS">预审通过</a-select-option>
            <a-select-option value="AUDIT_SUCCESS">终审通过</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit" :loading="loading">
            搜索
          </a-button>
          <a-button @click="handleReset" style="margin-left: 8px;">
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 案件列表 -->
    <a-card class="table-card" :body-style="{ padding: '20px' }">
      <a-table
        :columns="columns"
        :data-source="caseList"
        :pagination="pagination"
        :loading="loading"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'state'">
            <a-tag :color="getStatusColor(record.state?.code)">
              {{ record.state?.message }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'created'">
            {{ formatDate(record.created) }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-button 
              type="primary" 
              size="small"
              @click="handleOneClickEntrust(record)"
              :disabled="!canOneClickEntrust(record)"
            >
              一键委案
            </a-button>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { ReloadOutlined } from '@ant-design/icons-vue';
import { getReviewList } from '../server/api';
import dayjs from 'dayjs';

const router = useRouter();

// 响应式数据
const loading = ref(false);
const caseList = ref<any[]>([]);

// 搜索表单
const searchForm = reactive({
  batchName: '',
  state: ''
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
});

// 表格列配置
const columns = [
  {
    title: '序号',
    key: 'index',
    width: 80,
    align: 'center',
    customRender: ({ index }: { index: number }) => {
      return (pagination.current - 1) * pagination.pageSize + index + 1;
    }
  },
  {
    title: '案件ID',
    dataIndex: 'id',
    key: 'id',
    width: 160,
    ellipsis: true,
    align: 'center',
  },
  {
    title: '批次名称',
    dataIndex: 'batchName',
    key: 'batchName',
    align: 'left',
    width: 250,
    ellipsis: false,
  },
  {
    title: '委案商',
    dataIndex: 'entrustBName',
    key: 'entrustBName',
    align: 'center',
    width: 150,
    ellipsis: true
  },
  {
    title: '案件状态',
    key: 'state',
    align: 'center',
    width: 120,
  },
  {
    title: '创建时间',
    key: 'created',
    align: 'center',
    width: 180,
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    align: 'center',
    fixed: 'right'
  }
];

// 计算属性
const canOneClickEntrust = (record: any) => {
  const stateCode = record.state?.code;
  return stateCode === 'TO_AUDIT'; // 只有待审核的案件才能进行一键委案
};

// 生命周期
onMounted(() => {
  fetchCaseList();
});

// 获取案件列表
const fetchCaseList = async () => {
  loading.value = true;
  try {
    const params: any = {
      batchName: searchForm.batchName || '',
      state: searchForm.state || '',
      current: pagination.current,
      size: pagination.pageSize,
      tsToken: localStorage.getItem('tsToken') || ''
    };

    const result = await getReviewList(params);
    
    if (result.success && result.result) {
      caseList.value = result.result.records || [];
      pagination.total = result.result.total || 0;
    } else {
      message.error('获取案件列表失败');
      caseList.value = [];
    }
  } catch (error) {
    console.error('获取案件列表失败:', error);
    message.error('获取案件列表失败，请重试');
    caseList.value = [];
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  fetchCaseList();
};

// 重置搜索
const handleReset = () => {
  searchForm.batchName = '';
  searchForm.state = '';
  pagination.current = 1;
  fetchCaseList();
};

// 刷新
const handleRefresh = () => {
  fetchCaseList();
};

// 表格变化处理
const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  fetchCaseList();
};

// 一键委案
const handleOneClickEntrust = (record: any) => {
  if (!canOneClickEntrust(record)) {
    message.warning('该案件状态不支持一键委案操作');
    return;
  }
  
  // 跳转到一键委案详情页面
  router.push(`/one-click-case-detail/${record.id}`);
};


// 获取状态颜色
const getStatusColor = (stateCode: string) => {
  const colorMap: Record<string, string> = {
    'TO_AUDIT': 'orange',
    'PRE_AUDIT_SUCCESS': 'blue',
    'AUDIT_SUCCESS': 'green',
    'AUDIT_FAILED': 'red',
    'PRE_AUDIT_FAILED': 'red'
  };
  return colorMap[stateCode] || 'default';
};

// 格式化日期
const formatDate = (timestamp: number) => {
  if (!timestamp) return '-';
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');
};
</script>

<style scoped>
.one-click-case-list-container {
  height: 100%;
  padding: 24px;
  background-color: #f5f5f5;
  box-sizing: border-box;
}

.page-header {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 24px;
}

.filter-card,
.table-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 24px;
}

.table-card {
  margin-bottom: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .one-click-case-list-container {
    padding: 16px;
  }
  
  .filter-card,
  .table-card {
    margin-bottom: 16px;
  }
}
</style>
